package com.szbmyoubao.app.exception

import android.content.Context
import android.content.Intent
import android.os.Process
import com.szbmyoubao.app.ui.splash.SplashActivity
import com.ellecity06.common.utils.logD
import kotlin.system.exitProcess

/**
 * 全局异常捕获
 */
class GlobalExceptionHandler(private val context: Context) : Thread.UncaughtExceptionHandler {
    override fun uncaughtException(thread: Thread, throwable: Throwable) {
        // 记录崩溃信息（例如，写到文件、上传服务器等）
        logCrash(throwable)
        // 重启应用
        restartApplication()
    }

    private fun logCrash(throwable: Throwable) {
        // 示例：记录崩溃信息
        logD("出现异常=", tr = throwable)
    }

    private fun restartApplication() {
        val intent = Intent(context, SplashActivity::class.java) // 替换成你的主Activity
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)

        // 结束当前进程
        Process.killProcess(Process.myPid())
        exitProcess(1)
    }
}